import { parse } from '@babel/parser';
import generate from '@babel/generator';
import * as t from '@babel/types';
import { ITypeEntity, ITypeEntityField } from '@/types/modules/superType/types';
import { getTypeByParams } from '@/utils/editor-adapter/editorResource';

const logger: any = () => {};

const getVoIdByImportName = async function (typeName: string) {
  const typeItems = await getTypeByParams({
    name: typeName,
  });
  return typeItems?.[0]?._id || typeName;
};

// 辅助函数：安全获取对象属性值
const getObjectPropertyValue = (
  properties: (t.ObjectMethod | t.ObjectProperty | t.SpreadElement)[],
  keyName: string,
): any => {
  const prop = properties.find(
    (p): p is t.ObjectProperty =>
      t.isObjectProperty(p) && t.isIdentifier(p.key) && p.key.name === keyName,
  );

  if (!prop || !t.isExpression(prop.value)) return undefined;

  if (t.isStringLiteral(prop.value)) return prop.value.value;
  if (t.isNumericLiteral(prop.value)) return prop.value.value;
  if (t.isBooleanLiteral(prop.value)) return prop.value.value;
  if (t.isNullLiteral(prop.value)) return null;

  // 处理对象表达式
  if (t.isObjectExpression(prop.value)) {
    const obj: any = {};
    prop.value.properties.forEach((objProp) => {
      if (t.isObjectProperty(objProp) && t.isIdentifier(objProp.key)) {
        const key = objProp.key.name;
        if (t.isStringLiteral(objProp.value)) {
          obj[key] = objProp.value.value;
        } else if (t.isNumericLiteral(objProp.value)) {
          obj[key] = objProp.value.value;
        } else if (t.isBooleanLiteral(objProp.value)) {
          obj[key] = objProp.value.value;
        } else if (t.isArrayExpression(objProp.value)) {
          // 处理数组
          obj[key] = objProp.value.elements
            .map((el) => {
              if (t.isStringLiteral(el)) return el.value;
              if (t.isNumericLiteral(el)) return el.value;
              if (t.isBooleanLiteral(el)) return el.value;
              if (t.isObjectExpression(el)) {
                // 递归处理数组中的对象
                return getObjectPropertyValue(
                  [{ type: 'ObjectProperty', key: t.identifier('temp'), value: el } as any],
                  'temp',
                );
              }
              return null;
            })
            .filter((item) => item !== null);
        }
      }
    });
    return obj;
  }

  // 处理数组表达式
  if (t.isArrayExpression(prop.value)) {
    return prop.value.elements
      .map((el) => {
        if (t.isStringLiteral(el)) return el.value;
        if (t.isNumericLiteral(el)) return el.value;
        if (t.isBooleanLiteral(el)) return el.value;
        if (t.isObjectExpression(el)) {
          return getObjectPropertyValue(
            [{ type: 'ObjectProperty', key: t.identifier('temp'), value: el } as any],
            'temp',
          );
        }
        return null;
      })
      .filter((item) => item !== null);
  }

  // 处理其他复杂表达式（如函数调用、成员表达式等）
  // 使用 parseLiteralValue 来处理复杂的表达式
  const parsedValue = parseLiteralValue(prop.value);
  if (parsedValue && typeof parsedValue === 'object' && parsedValue.type === 'JSExpression') {
    return parsedValue.value;
  }

  return undefined;
};

// 增强的注释解析函数
const parseComments = (sourceCode: string): string => {
  // 匹配多行 JSDoc 注释
  const multiLineMatch = sourceCode.match(/\/\*\*([\s\S]*?)\*\//);
  if (multiLineMatch) {
    const commentContent = multiLineMatch[1];
    // 清理注释格式，移除 * 符号和多余空格
    const lines = commentContent
      .split('\n')
      .map((line) => line.replace(/^\s*\*\s?/, '').trim())
      .filter((line) => line.length > 0);
    return lines.join('\n');
  }

  // 匹配单行注释
  const singleLineMatch = sourceCode.match(/\/\*\*\s*([^*\n]+)/);
  if (singleLineMatch) {
    return singleLineMatch[1].trim();
  }

  return '';
};

// 解析字段注释，提取描述和示例
const parseFieldComment = (
  comments: t.Comment[] | null | undefined,
): { desc: string; example?: any } => {
  if (!comments || comments.length === 0) return { desc: '' };

  const comment = comments[0].value.trim();

  // 如果是分隔线注释，返回空字符串
  if (comment.includes('=====') || comment.match(/^[=\-\*\s]+$/)) {
    return { desc: '' };
  }

  // 提取有意义的注释内容
  const lines = comment
    .split('\n')
    .map((line) => line.replace(/^\s*\*?\s?/, '').trim())
    .filter((line) => line.length > 0 && !line.match(/^[=\-\*\s]+$/));

  const fullComment = lines.join(' ');

  // 查找 @example 标记
  const exampleMatch = fullComment.match(/@example\s+(.+?)(?:\s+@|$)/);
  let desc = fullComment;
  let example: any = undefined;

  if (exampleMatch) {
    // 提取示例值
    const exampleStr = exampleMatch[1].trim();
    desc = fullComment.replace(/@example\s+.+/, '').trim();

    // 尝试解析示例值
    try {
      // 如果是JSON格式，解析为对象
      if (exampleStr.startsWith('{') || exampleStr.startsWith('[')) {
        example = JSON.parse(exampleStr);
      } else if (exampleStr === 'true' || exampleStr === 'false') {
        example = exampleStr === 'true';
      } else if (!isNaN(Number(exampleStr))) {
        example = Number(exampleStr);
      } else {
        example = exampleStr;
      }
    } catch (e) {
      // 解析失败，保持字符串格式
      example = exampleStr;
    }
  }

  return { desc, example };
};

export async function parseTsType(
  type: string,
  format: 'string' | 'object' = 'string',
  className?: string,
): Promise<string | ITypeEntity> {
  try {
    logger('开始解析 TypeScript 代码，长度:', type.length);
    logger('代码片段预览:', type.substring(0, 200));

    const ast = parse(type, {
      sourceType: 'module',
      plugins: ['typescript', 'decorators-legacy', 'classProperties'],
      errorRecovery: true,
    });

    logger('AST 解析成功，program.body 长度:', ast.program.body.length);

    // 根据是否传入className来决定查找策略
    logger('查找类声明，目标类名:', className);
    logger(
      'AST program.body 节点类型:',
      ast.program.body.map((node) => node.type),
    );

    let classDeclaration: any;
    if (className) {
      // 精准查找指定类名的类声明
      logger(`精准查找类名为 "${className}" 的类声明`);
      classDeclaration = ast.program.body.find((node) => {
        logger('检查节点类型:', node.type);
        if (t.isClassDeclaration(node)) {
          logger('找到类声明，类名:', node.id?.name);
          if (t.isIdentifier(node.id) && node.id.name === className) {
            logger(`匹配到目标类: ${className}`);
            return true;
          }
        }
        if (t.isExportNamedDeclaration(node) && t.isClassDeclaration(node.declaration)) {
          const classDecl = node.declaration;
          logger('找到导出的类声明，类名:', classDecl.id?.name);
          if (t.isIdentifier(classDecl.id) && classDecl.id.name === className) {
            logger(`匹配到目标导出类: ${className}`);
            return true;
          }
        }
        return false;
      });
    } else {
      // 兼容原有逻辑：查找第一个类声明
      logger('查找第一个类声明');
      classDeclaration = ast.program.body.find(
        (node) =>
          t.isClassDeclaration(node) ||
          (t.isExportNamedDeclaration(node) && t.isClassDeclaration(node.declaration)),
      );
    }

    logger('找到的类声明:', classDeclaration ? classDeclaration.type : 'null');

    let realClassDeclaration = classDeclaration;
    if (t.isExportNamedDeclaration(classDeclaration)) {
      realClassDeclaration = classDeclaration.declaration;
    }
    if (!realClassDeclaration || !t.isClassDeclaration(realClassDeclaration)) {
      const errorMsg = className
        ? `No class declaration found with name: ${className}`
        : 'No class declaration found';
      throw new Error(errorMsg);
    }

    const typeEntity: ITypeEntity = {
      name: t.isIdentifier(realClassDeclaration.id) ? realClassDeclaration.id.name : '',
      desc: '',
      type: 'vo',
      fields: [],
    };

    // 增强的注释解析
    typeEntity.desc = parseComments(type);

    // 收集类级别的索引信息
    const classIndexes: any[] = [];

    // 处理类级别的装饰器
    if (realClassDeclaration.decorators) {
      realClassDeclaration.decorators.forEach((decorator: any) => {
        if (
          t.isCallExpression(decorator.expression) &&
          t.isIdentifier(decorator.expression.callee)
        ) {
          const decoratorName = decorator.expression.callee.name;

          if (decoratorName === 'Entity') {
            const [options] = decorator.expression.arguments;
            if (options && t.isObjectExpression(options)) {
              typeEntity.db = {
                name: getObjectPropertyValue(options.properties, 'name'),
                database: getObjectPropertyValue(options.properties, 'database'),
                type: getObjectPropertyValue(options.properties, 'type') || 'postgres', // 提供默认值
              };
              logger('Entity 配置:', typeEntity.db);
            }
          } else if (decoratorName === 'Index') {
            // 解析索引装饰器
            const [columns, options] = decorator.expression.arguments;
            const indexInfo: any = {};

            if (t.isArrayExpression(columns)) {
              indexInfo.columns = columns.elements
                .filter((el): el is t.StringLiteral => t.isStringLiteral(el))
                .map((el) => el.value);
            }

            if (options && t.isObjectExpression(options)) {
              indexInfo.unique = getObjectPropertyValue(options.properties, 'unique');
              indexInfo.where = getObjectPropertyValue(options.properties, 'where');
              indexInfo.name = getObjectPropertyValue(options.properties, 'name');
            }

            classIndexes.push(indexInfo);
            logger('Index 配置:', indexInfo);
          }
        }
      });
    }

    // 如果有索引信息，添加到 db 配置中
    if (classIndexes.length > 0) {
      if (!typeEntity.db) typeEntity.db = {};
      (typeEntity.db as any).indexes = classIndexes;
    }

    for (const member of realClassDeclaration.body.body) {
      if (t.isClassProperty(member)) {
        const commentData = parseFieldComment(member.leadingComments);
        const field: ITypeEntityField = {
          name: t.isIdentifier(member.key) ? member.key.name : '',
          desc: commentData.desc,
          example: commentData.example,
          required: !member.optional,
          type: 'string', // 默认类型
          isArray: false,
          isApi: false,
        };

        // 处理装饰器
        if (member.decorators && member.decorators.length > 0) {
          for (const decorator of member.decorators) {
            if (
              t.isCallExpression(decorator.expression) &&
              t.isIdentifier(decorator.expression.callee)
            ) {
              const decoratorName = decorator.expression.callee.name;
              logger('当前处理的装饰器名称:', decoratorName);

              // 处理 Form 装饰器（用于 IProps 字段的 setter 配置）
              if (decoratorName === 'Form') {
                logger('处理 Form 装饰器');
                const [options] = decorator.expression.arguments;
                if (options && t.isObjectExpression(options)) {
                  // 解析 setter 配置
                  const setter = getObjectPropertyValue(options.properties, 'setter');
                  const setterProps = getObjectPropertyValue(options.properties, 'setterProps');

                  if (setter) {
                    field.setter = setter;
                  }

                  if (setterProps) {
                    // setterProps 应该保持为对象格式
                    if (typeof setterProps === 'object' && setterProps !== null) {
                      field.setterProps = setterProps;
                    } else if (typeof setterProps === 'string') {
                      try {
                        // 如果是字符串，尝试解析为对象
                        field.setterProps = JSON.parse(setterProps);
                        logger('成功解析 setterProps 字符串:', field.setterProps);
                      } catch (e) {
                        // 如果解析失败，将字符串包装为对象
                        field.setterProps = { template: setterProps };
                        logger('setterProps 解析失败，包装为对象:', field.setterProps);
                      }
                    }
                  }

                  logger('Form 装饰器解析结果:', {
                    setter: field.setter,
                    setterProps: field.setterProps,
                  });
                }
              }

              // 处理 TypeORM 装饰器
              else if (decoratorName === 'Column') {
                logger('处理 Column 装饰器');
                const [options] = decorator.expression.arguments;
                if (options && t.isObjectExpression(options)) {
                  if (!field.db) field.db = {};
                  field.db = {
                    ...field.db,
                    type: getObjectPropertyValue(options.properties, 'type'),
                    length: getObjectPropertyValue(options.properties, 'length'),
                    precision: getObjectPropertyValue(options.properties, 'precision'),
                    scale: getObjectPropertyValue(options.properties, 'scale'),
                    nullable: getObjectPropertyValue(options.properties, 'nullable'),
                    default: getObjectPropertyValue(options.properties, 'default'),
                    comment: getObjectPropertyValue(options.properties, 'comment'),
                    isPrimary: getObjectPropertyValue(options.properties, 'primary'),
                  };
                  logger('Column 装饰器解析结果:', field.db);
                }
              } else if (decoratorName === 'Index') {
                logger('处理字段级 Index 装饰器');
                const [options] = decorator.expression.arguments;
                if (options && t.isObjectExpression(options)) {
                  if (!field.db) field.db = {};
                  const indexOptions = {
                    unique: getObjectPropertyValue(options.properties, 'unique'),
                    where: getObjectPropertyValue(options.properties, 'where'),
                    nullFiltered: getObjectPropertyValue(options.properties, 'nullFiltered'),
                    fulltext: getObjectPropertyValue(options.properties, 'fulltext'),
                    parser: getObjectPropertyValue(options.properties, 'parser'),
                    spatial: getObjectPropertyValue(options.properties, 'spatial'),
                    concurrent: getObjectPropertyValue(options.properties, 'concurrent'),
                    sparse: getObjectPropertyValue(options.properties, 'sparse'),
                    background: getObjectPropertyValue(options.properties, 'background'),
                    expireAfterSeconds: getObjectPropertyValue(
                      options.properties,
                      'expireAfterSeconds',
                    ),
                  };
                  field.db = { ...field.db, ...indexOptions };
                  logger('Index 装饰器解析结果:', field.db);
                }
              } else if (decoratorName === 'JoinColumn') {
                logger('处理 JoinColumn 装饰器');
                const [options] = decorator.expression.arguments;
                if (options && t.isObjectExpression(options)) {
                  if (!field.db) field.db = {};
                  const foreignKey = {
                    table: (field as any).relation?.target || '',
                    column: getObjectPropertyValue(options.properties, 'name') || 'id',
                    onDelete: getObjectPropertyValue(options.properties, 'onDelete'),
                    onUpdate: getObjectPropertyValue(options.properties, 'onUpdate'),
                  };
                  field.db.foreignKey = foreignKey;
                  logger('JoinColumn 装饰器解析结果:', field.db.foreignKey);
                }
              } else if (decoratorName === 'DataSource' || decoratorName === 'dataSource') {
                logger('处理 DataSource/dataSource 装饰器');
                const [options] = decorator.expression.arguments;
                if (options && t.isObjectExpression(options)) {
                  // 使用老版本的完整处理逻辑
                  const apiOptions: any = {};
                  options.properties.forEach((prop) => {
                    if (
                      t.isObjectProperty(prop) &&
                      t.isIdentifier(prop.key) &&
                      t.isExpression(prop.value)
                    ) {
                      apiOptions[prop.key.name] = parseLiteralValue(prop.value);
                    }
                  });

                  field.isApi = true;

                  // 处理 isInit 字段
                  if (typeof apiOptions.isInit === 'boolean') {
                    field.isInit = apiOptions.isInit;
                    delete apiOptions.isInit;
                  }

                  // 处理 isSync 字段
                  if (typeof apiOptions.isSync === 'boolean') {
                    field.isSync = apiOptions.isSync;
                    delete apiOptions.isSync;
                  }

                  // 处理 api 字段
                  if (typeof apiOptions.api === 'string' && apiOptions.api) {
                    field.apiImport = apiOptions.api;
                    // 根据api 的uri+method获取API TypeItem
                    const apiTypeItems = await getTypeByParams({
                      uri: apiOptions.api,
                      method: apiOptions.method,
                    });
                    if (apiTypeItems.length > 0) {
                      field.apiImportEntity = apiTypeItems[0];
                      field.apiImport = apiTypeItems[0]._id;
                    } else {
                      console.warn('API TypeItem not found 需要完成加载远程资源', apiOptions.api);
                    }
                    delete apiOptions.api;
                  }

                  field.apiOptions = apiOptions;
                  logger('DataSource/dataSource 装饰器解析结果:', field.apiOptions);
                  logger('字段标记为API字段:', field.isApi);
                }
              }
            } else if (t.isIdentifier(decorator.expression)) {
              const decoratorName = decorator.expression.name;
              logger('当前处理的标识符装饰器名称:', decoratorName);

              if (decoratorName === 'PrimaryGeneratedColumn') {
                logger('处理 PrimaryGeneratedColumn 装饰器');
                if (!field.db) field.db = {};
                field.db = {
                  ...field.db,
                  isPrimary: true,
                  isGenerated: true,
                };
                logger('PrimaryGeneratedColumn 装饰器解析结果:', field.db);
              }
            }
          }
        }

        // 处理类型注解
        if (member.typeAnnotation && t.isTSTypeAnnotation(member.typeAnnotation)) {
          const typeAnnotation = member.typeAnnotation.typeAnnotation;

          if (t.isTSStringKeyword(typeAnnotation)) {
            field.type = 'string';
          } else if (t.isTSNumberKeyword(typeAnnotation)) {
            field.type = 'number';
          } else if (t.isTSBooleanKeyword(typeAnnotation)) {
            field.type = 'boolean';
          } else if (t.isTSObjectKeyword(typeAnnotation) || t.isTSAnyKeyword(typeAnnotation)) {
            field.type = 'object';
          } else if (t.isTSFunctionType(typeAnnotation)) {
            // 处理函数类型签名，如 (a: string, b: number) => void
            field.type = 'function';

            // 解析函数参数生成 template
            if (!field.setter) {
              field.setter = 'FunctionSetter';
              if (!field.setterProps) {
                try {
                  logger('函数类型注解结构:', JSON.stringify(typeAnnotation, null, 2));

                  // 使用 generate 来获取完整的函数签名，然后解析参数
                  const functionSignature = generate(typeAnnotation).code;
                  logger('函数签名:', functionSignature);

                  // 使用正则表达式从函数签名中提取参数
                  const paramMatch = functionSignature.match(/\(([^)]*)\)/);
                  let params = '';

                  if (paramMatch && paramMatch[1]) {
                    // 解析参数列表，去除类型注解
                    const paramList = paramMatch[1]
                      .split(',')
                      .map((param) => {
                        // 去除类型注解，只保留参数名
                        const paramName = param.trim().split(':')[0].trim();
                        return paramName || 'param';
                      })
                      .filter((name) => name && name !== 'param')
                      .join(', ');

                    params = paramList;
                    logger('解析出的参数:', params);
                  }

                  // 如果没有解析出参数，尝试直接从 AST 获取
                  if (!params && (typeAnnotation as any).parameters) {
                    params = (typeAnnotation as any).parameters
                      .map((param: any, index: number) => {
                        logger(`AST参数 ${index}:`, param);

                        // 尝试多种方式获取参数名
                        if (param.name && t.isIdentifier(param.name)) {
                          return param.name.name;
                        }
                        if (param.parameter && t.isIdentifier(param.parameter)) {
                          return param.parameter.name;
                        }
                        if (t.isIdentifier(param)) {
                          return param.name;
                        }
                        if (param.left && t.isIdentifier(param.left)) {
                          return param.left.name;
                        }

                        return `param${index + 1}`;
                      })
                      .join(', ');
                  }

                  field.setterProps = {
                    template: `${field.name}(${params}){}`,
                  };

                  logger(`为函数类型 ${field.name} 生成模板:`, field.setterProps.template);
                } catch (e) {
                  // 如果解析失败，使用默认模板
                  field.setterProps = {
                    template: `${field.name}(e){}`,
                  };
                  logger(`函数类型解析失败，使用默认模板:`, field.setterProps.template, e);
                }
              }
            }
          } else if (t.isTSTypeReference(typeAnnotation)) {
            if (t.isIdentifier(typeAnnotation.typeName)) {
              // 特殊处理 Date 类型
              if (typeAnnotation.typeName.name === 'Date') {
                field.type = 'Date';
              } else if (typeAnnotation.typeName.name === 'Function') {
                // 处理 Function 类型
                field.type = 'function';

                // 为 Function 类型设置默认的 setter 配置
                if (!field.setter) {
                  field.setter = 'FunctionSetter';
                }

                // 如果没有 setterProps，设置默认模板
                if (!field.setterProps) {
                  field.setterProps = {
                    template: `${field.name}(e){}`,
                  };
                } else {
                  // 如果已经有 setterProps（来自 @Form 装饰器），检查是否需要处理
                  let setterProps = field.setterProps;

                  // 如果 setterProps 是字符串，尝试解析
                  if (typeof setterProps === 'string') {
                    try {
                      setterProps = JSON.parse(setterProps);
                      field.setterProps = setterProps;
                    } catch (e) {
                      // 解析失败，保持原值
                    }
                  }

                  logger(`Function 类型 ${field.name} 已有 setterProps:`, field.setterProps);
                }
              } else if (typeAnnotation.typeName.name === 'Array') {
                // 特殊处理 Array<T> 类型
                field.isArray = true;

                // 检查是否有泛型参数来确定数组元素类型
                if (
                  typeAnnotation.typeParameters &&
                  t.isTSTypeParameterInstantiation(typeAnnotation.typeParameters)
                ) {
                  const params = typeAnnotation.typeParameters.params;
                  if (params.length > 0) {
                    const elementType = params[0];

                    if (t.isTSStringKeyword(elementType)) {
                      field.type = 'string';
                    } else if (t.isTSNumberKeyword(elementType)) {
                      field.type = 'number';
                    } else if (t.isTSBooleanKeyword(elementType)) {
                      field.type = 'boolean';
                    } else if (t.isTSObjectKeyword(elementType) || t.isTSAnyKeyword(elementType)) {
                      field.type = 'object';
                    } else if (t.isTSTypeLiteral(elementType)) {
                      // 处理 Array<{id: number, title: string}> 这种对象字面量数组
                      field.type = 'object';
                      logger('检测到 Array 元素为对象类型字面量:', field.name);

                      // 使用通用函数解析字段结构
                      field.fields = parseTypeLiteralFields(
                        elementType,
                        `${field.name}[]`,
                        'Array 元素对象字面量',
                      );
                    } else if (
                      t.isTSTypeReference(elementType) &&
                      t.isIdentifier(elementType.typeName)
                    ) {
                      // 处理 Array<SomeType> 这种引用类型数组
                      field.type = 'object';
                      field.import = await getVoIdByImportName(elementType.typeName.name);
                      logger('Array 元素类型引用:', elementType.typeName.name);
                    } else {
                      // 默认为 object 类型
                      field.type = 'object';
                    }
                  } else {
                    // 没有泛型参数，默认为 any[]
                    field.type = 'object';
                  }
                } else {
                  // 没有泛型参数，默认为 any[]
                  field.type = 'object';
                }
              } else {
                field.type = 'object';

                // 使用辅助函数处理泛型参数
                const actualTypeName = extractActualTypeFromGeneric(typeAnnotation);

                // 处理泛型包装类型
                if (actualTypeName) {
                  logger('import = 数组元素的泛型实际类型:', actualTypeName);
                  field.import = await getVoIdByImportName(actualTypeName);

                  // 记录原始泛型类型名称，用于调试
                  if (t.isIdentifier(typeAnnotation.typeName)) {
                    const wrapperName = typeAnnotation.typeName.name;

                    // 特殊处理常见的泛型包装类型
                    const genericWrappers = [
                      'Partial',
                      'Pick',
                      'Omit',
                      'Record',
                      'Required',
                      'Readonly',
                    ];
                    if (genericWrappers.includes(wrapperName)) {
                      logger(
                        '检测到泛型包装类型:',
                        wrapperName,
                        '，使用实际类型:',
                        actualTypeName,
                      );

                      // 可以在这里根据不同的包装类型添加特殊处理逻辑
                      if (wrapperName === 'Partial') {
                        logger('Partial类型字段，所有属性可能为可选');
                        // 可以在这里设置一些标记，表示这是一个Partial类型
                      }
                    }
                  }
                } else {
                  // 检查是否为泛型包装类型（如 Partial<any>）
                  if (t.isIdentifier(typeAnnotation.typeName)) {
                    const wrapperName = typeAnnotation.typeName.name;
                    const genericWrappers = [
                      'Partial',
                      'Pick',
                      'Omit',
                      'Record',
                      'Required',
                      'Readonly',
                    ];

                    if (genericWrappers.includes(wrapperName)) {
                      logger('检测到泛型包装类型但无法提取具体类型:', wrapperName);
                      // 对于 Partial<any> 这种情况，不设置 import，保持为 object 类型
                      // field.import 保持为 undefined
                    } else {
                      logger('import = 数组元素的原始类型名称:', typeAnnotation.typeName.name);
                      field.import = await getVoIdByImportName(typeAnnotation.typeName.name);
                    }
                  } else {
                    logger('无法识别的类型名称结构');
                  }
                }
              }
            }
          } else if (t.isTSFunctionType(typeAnnotation)) {
            // 处理 TypeScript 函数类型，如 () => void, (param: string) => number
            // field.type = 'function';

            // // 尝试生成函数签名描述
            // try {
            //   const params = typeAnnotation.parameters
            //     .map((param) => {
            //       if (
            //         t.isIdentifier(param) &&
            //         param.typeAnnotation &&
            //         t.isTSTypeAnnotation(param.typeAnnotation)
            //       ) {
            //         const paramType = generate(param.typeAnnotation.typeAnnotation).code;
            //         return `${param.name}: ${paramType}`;
            //       } else if (t.isIdentifier(param)) {
            //         return param.name;
            //       }
            //       return 'param';
            //     })
            //     .join(', ');

            //   const returnType = typeAnnotation.typeAnnotation
            //     ? generate(typeAnnotation.typeAnnotation).code
            //     : 'void';

            //   field.functionSignature = `(${params}) => ${returnType}`;
            //   logger('解析到函数类型签名:', field.functionSignature);
            // } catch (e) {
            //   console.warn('解析函数签名失败:', e);
            // }
            console.error('上面代码注释了，之前AI说的是永远无法触发这种情况');
            debugger;
          } else if (t.isTSTypeLiteral(typeAnnotation)) {
            // 处理对象类型字面量，如 { ab: number; f: number; }
            field.type = 'object';
            logger('检测到对象类型字面量:', field.name);

            // 使用通用函数解析字段结构
            field.fields = parseTypeLiteralFields(typeAnnotation, field.name);
          } else if (t.isTSArrayType(typeAnnotation)) {
            field.isArray = true;
            const elementType = typeAnnotation.elementType;

            if (t.isTSStringKeyword(elementType)) {
              field.type = 'string';
            } else if (t.isTSNumberKeyword(elementType)) {
              field.type = 'number';
            } else if (t.isTSBooleanKeyword(elementType)) {
              field.type = 'boolean';
            } else if (t.isTSObjectKeyword(elementType) || t.isTSAnyKeyword(elementType)) {
              field.type = 'object';
            } else if (t.isTSTypeLiteral(elementType)) {
              // 处理数组元素为对象类型字面量的情况，如 { label: string, value: string }[]
              field.type = 'object';
              logger('检测到数组元素为对象类型字面量:', field.name);

              // 使用通用函数解析字段结构
              field.fields = parseTypeLiteralFields(
                elementType,
                `${field.name}[]`,
                '数组元素对象字面量',
              );
            } else if (t.isTSTypeReference(elementType)) {
              field.type = 'object';
              if (t.isIdentifier(elementType.typeName)) {
                // 处理数组元素的泛型类型
                if (
                  elementType.typeParameters &&
                  t.isTSTypeParameterInstantiation(elementType.typeParameters)
                ) {
                  const params = elementType.typeParameters.params;

                  // 处理数组元素的泛型包装类型
                  if (params[0]) {
                    // 检查是否为 any 类型
                    if (t.isTSAnyKeyword(params[0])) {
                      logger('数组元素的泛型参数为 any 类型，不设置 import');
                      // 对于 Partial<any>[] 这种情况，不设置 import，保持为 object 类型
                      if (t.isIdentifier(elementType.typeName)) {
                        const wrapperName = elementType.typeName.name;
                        logger('检测到数组元素的泛型包装类型但参数为 any:', wrapperName);
                      }
                    } else if (
                      t.isTSTypeReference(params[0]) &&
                      t.isIdentifier(params[0].typeName)
                    ) {
                      const actualTypeName = params[0].typeName.name;
                      logger('import = 数组元素的泛型实际类型:', actualTypeName);
                      field.import = await getVoIdByImportName(actualTypeName);

                      // 记录原始泛型类型名称，用于调试
                      if (t.isIdentifier(elementType.typeName)) {
                        logger('数组元素的原始泛型包装类型名称:', elementType.typeName.name);

                        // 特殊处理常见的泛型包装类型
                        const genericWrappers = [
                          'Partial',
                          'Pick',
                          'Omit',
                          'Record',
                          'Required',
                          'Readonly',
                        ];
                        if (genericWrappers.includes(elementType.typeName.name)) {
                          logger(
                            '检测到数组元素的泛型包装类型:',
                            elementType.typeName.name,
                            '，使用实际类型:',
                            actualTypeName,
                          );
                        }
                      }
                    }
                  }
                } else {
                  // 检查是否为泛型包装类型（如 Partial<any>）
                  if (t.isIdentifier(elementType.typeName)) {
                    const wrapperName = elementType.typeName.name;
                    const genericWrappers = [
                      'Partial',
                      'Pick',
                      'Omit',
                      'Record',
                      'Required',
                      'Readonly',
                    ];

                    if (genericWrappers.includes(wrapperName)) {
                      logger('检测到数组元素的泛型包装类型但无法提取具体类型:', wrapperName);
                      // 对于 Partial<any>[] 这种情况，不设置 import，保持为 object 类型
                      // field.import 保持为 undefined
                    } else {
                      logger('import = 数组元素的原始类型名称:', elementType.typeName.name);
                      field.import = await getVoIdByImportName(elementType.typeName.name);
                    }
                  } else {
                    logger('无法识别的数组元素类型名称结构');
                  }
                }
              }
            }
          }
        }

        // 处理默认值
        if (member.value) {
          const rawDefault = parseLiteralValue(member.value);
          field.default = processSpecialDefaultValue(rawDefault, 'mysql');
        }

        // 处理装饰器中的默认值
        if (field.db?.default) {
          const processedDefault = processSpecialDefaultValue(field.db.default, 'mysql');

          // 如果是特殊的数据库函数，设置到字段的默认值
          if (
            typeof processedDefault === 'string' &&
            ['CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME', 'UUID_GENERATE'].includes(
              processedDefault,
            )
          ) {
            field.default = processedDefault;
            // 同时在 db 配置中保留原始信息
            (field.db as any).defaultType = 'function';
            (field.db as any).defaultFunction = processedDefault;
          } else {
            field.default = processedDefault;
          }
        }

        typeEntity.fields.push(field);
      }
    }

    if (format === 'object') {
      return typeEntity;
    }
    return JSON.stringify(typeEntity, null, 2);
  } catch (error) {
    console.error('Failed to parse TypeScript type:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);

    // 尝试简化代码再次解析
    if (className && type.includes(`class ${className}`)) {
      logger('尝试提取并简化类定义');
      const classStart = type.indexOf(`class ${className}`);
      const classEnd = type.indexOf('\n}', classStart) + 2;
      if (classStart !== -1 && classEnd > classStart) {
        const simplifiedClass = type.substring(classStart, classEnd);
        logger('简化的类定义:', simplifiedClass);

        try {
          const simpleAst = parse(simplifiedClass, {
            sourceType: 'module',
            plugins: ['typescript', 'decorators-legacy', 'classProperties'],
            errorRecovery: true,
          });

          logger('简化版本解析成功');
          // 这里可以继续处理简化版本的 AST
        } catch (simpleError) {
          console.error('简化版本也解析失败:', simpleError.message);
        }
      }
    }

    return '';
  }
}

// 特殊默认值处理函数 - 增强版
const processSpecialDefaultValue = (defaultValue: any, dbType: string = 'mysql'): any => {
  // 处理函数表达式默认值
  if (typeof defaultValue === 'function') {
    try {
      const result = defaultValue();

      // 常见的数据库函数映射
      const dbFunctionMap: Record<string, string> = {
        CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP',
        'NOW()': 'CURRENT_TIMESTAMP',
        CURRENT_DATE: 'CURRENT_DATE',
        CURRENT_TIME: 'CURRENT_TIME',
        'UUID()': 'UUID_GENERATE',
        'NEWID()': 'UUID_GENERATE',
      };

      return dbFunctionMap[result] || result;
    } catch (e) {
      // 复杂函数表达式，保持原样
      return {
        type: 'JSFunction',
        value: generate(defaultValue).code,
      };
    }
  }

  // 处理字符串类型的特殊值
  if (typeof defaultValue === 'string') {
    const specialValues = [
      'CURRENT_TIMESTAMP',
      'CURRENT_DATE',
      'CURRENT_TIME',
      'UUID_GENERATE',
      'AUTO_INCREMENT',
    ];

    if (specialValues.includes(defaultValue)) {
      return defaultValue; // 保持字符串形式，方便表单处理
    }
  }

  return defaultValue;
};

// 改进的递归解析函数 - 基于老版本的 processObjectValue
function parseLiteralValue(node: t.Expression | null): any {
  if (!node) return null;

  // 处理ConditionalExpression (三元操作符)
  if (t.isConditionalExpression(node)) {
    const test = parseLiteralValue(node.test);
    const consequent = parseLiteralValue(node.consequent);
    const alternate = parseLiteralValue(node.alternate);

    const testValue = typeof test === 'object' && test !== null ? test.value : test;
    const consequentValue =
      typeof consequent === 'object' && consequent !== null
        ? consequent.value
        : typeof consequent === 'string'
        ? `"${consequent}"`
        : consequent;
    const alternateValue =
      typeof alternate === 'object' && alternate !== null
        ? alternate.value
        : typeof alternate === 'string'
        ? `"${alternate}"`
        : alternate;

    const expression = `${testValue} ? ${consequentValue} : ${alternateValue}`;

    return {
      type: 'JSExpression',
      value: expression,
    };
  }

  // 处理LogicalExpression
  if (t.isLogicalExpression(node)) {
    const left = parseLiteralValue(node.left);
    const right = parseLiteralValue(node.right);

    // 更仔细地处理左右值
    let leftValue = '';
    if (left === null) {
      leftValue = 'null';
    } else if (typeof left === 'object' && left !== null) {
      leftValue = left.value || '';
    } else {
      leftValue = String(left || '');
    }

    let rightValue = '';
    if (right === null) {
      rightValue = 'null';
    } else if (typeof right === 'object' && right !== null) {
      rightValue = right.value || '';
    } else {
      rightValue = String(right || '');
    }

    // 特殊处理：如果右侧是字符串字面量，需要保留引号
    if (t.isStringLiteral(node.right)) {
      rightValue = `'${node.right.value}'`;
    } else if (t.isNullLiteral(node.right)) {
      rightValue = 'null';
    }

    const expression = `${leftValue} ${node.operator} ${rightValue}`;

    return {
      type: 'JSExpression',
      value: expression,
    };
  }

  // 处理OptionalMemberExpression
  if (t.isOptionalMemberExpression(node)) {
    // 构建表达式链，收集所有属性
    const chain: string[] = [];
    let current: t.Expression | t.V8IntrinsicIdentifier = node;

    // 向上遍历，收集所有可选链属性
    while (t.isOptionalMemberExpression(current)) {
      const property = current.property;
      if (t.isIdentifier(property)) {
        chain.unshift(property.name); // 插入到数组开头，保持正确顺序
      }
      current = current.object;
    }

    // 处理基础对象部分
    let baseExpression = '';

    // 处理嵌套的CallExpression情况，如this.utils.getRoute()?.query
    if (t.isCallExpression(current)) {
      const callee = current.callee;
      if (t.isMemberExpression(callee)) {
        let callExpr = '';
        let temp: t.Expression | t.V8IntrinsicIdentifier = callee;
        while (t.isMemberExpression(temp)) {
          const prop = temp.property;
          if (t.isIdentifier(prop)) {
            callExpr = prop.name + (callExpr ? '.' + callExpr : '');
          }
          temp = temp.object;
        }
        if (t.isThisExpression(temp)) {
          callExpr = 'this.' + callExpr;
        } else if (t.isIdentifier(temp)) {
          callExpr = temp.name + '.' + callExpr;
        }

        // 添加函数调用括号和参数
        if (current.arguments && current.arguments.length > 0) {
          callExpr +=
            '(' +
            current.arguments
              .map((arg) => {
                if (t.isExpression(arg)) {
                  if (t.isStringLiteral(arg)) {
                    return `'${arg.value}'`;
                  }
                  const result = parseLiteralValue(arg);
                  return result !== null ? result : '';
                }
                return '';
              })
              .filter(Boolean)
              .join(', ') +
            ')';
        } else {
          callExpr += '()';
        }

        baseExpression = callExpr;
      }
    } else if (t.isMemberExpression(current)) {
      // 处理普通的成员表达式，如 this.props
      let memberChain = '';
      let temp: t.Expression | t.V8IntrinsicIdentifier = current;
      while (t.isMemberExpression(temp)) {
        const property = temp.property;
        if (t.isIdentifier(property)) {
          memberChain = property.name + (memberChain ? '.' + memberChain : '');
        }
        temp = temp.object;
      }
      if (t.isThisExpression(temp)) {
        baseExpression = 'this.' + memberChain;
      } else if (t.isIdentifier(temp)) {
        baseExpression = temp.name + '.' + memberChain;
      }
    } else if (t.isThisExpression(current)) {
      baseExpression = 'this';
    } else if (t.isIdentifier(current)) {
      baseExpression = current.name;
    }

    // 拼接完整表达式：基础部分 + 可选链部分
    const fullExpression = baseExpression + (chain.length > 0 ? '?.' + chain.join('.') : '');

    return {
      type: 'JSExpression',
      value: fullExpression,
    };
  }

  if (t.isStringLiteral(node)) return node.value;
  if (t.isNumericLiteral(node)) return node.value;
  if (t.isBooleanLiteral(node)) return node.value;
  if (t.isNullLiteral(node)) return null;

  if (t.isIdentifier(node)) {
    return {
      type: 'JSExpression',
      value: node.name,
    };
  }

  if (t.isMemberExpression(node)) {
    // 处理 this.props.project_id 这种情况
    let current: t.Expression | t.V8IntrinsicIdentifier = node;
    let expression = '';
    while (t.isMemberExpression(current)) {
      const property = current.property;
      if (t.isIdentifier(property)) {
        expression = property.name + (expression ? '.' + expression : '');
      }
      current = current.object;
    }
    if (t.isThisExpression(current)) {
      expression = 'this.' + expression;
    } else if (t.isIdentifier(current)) {
      expression = current.name + '.' + expression;
    }
    return {
      type: 'JSExpression',
      value: expression,
    };
  }

  if (t.isCallExpression(node)) {
    // 处理函数调用表达式
    let expression = '';
    const callee = node.callee;
    if (t.isMemberExpression(callee)) {
      // 处理 this.utils.getGlobalData('currentShopId') 这种情况
      let current: t.Expression | t.V8IntrinsicIdentifier = callee;
      while (t.isMemberExpression(current)) {
        const property = current.property;
        if (t.isIdentifier(property)) {
          expression = property.name + (expression ? '.' + expression : '');
        }
        current = current.object;
      }
      if (t.isThisExpression(current)) {
        expression = 'this.' + expression;
      }
    }

    // 添加参数 - 修复：无论是否有参数都要添加括号
    if (node.arguments && node.arguments.length > 0) {
      expression +=
        '(' +
        node.arguments
          .map((arg) => {
            if (t.isExpression(arg)) {
              if (t.isStringLiteral(arg)) {
                return `'${arg.value}'`;
              }
              const result = parseLiteralValue(arg);
              return result !== null ? result : '';
            }
            return '';
          })
          .filter(Boolean)
          .join(', ') +
        ')';
    } else {
      // 即使没有参数也要添加空括号
      expression += '()';
    }

    return {
      type: 'JSExpression',
      value: expression,
    };
  }

  if (t.isArrayExpression(node)) {
    return node.elements.map((el) => {
      if (!el) return null;
      if (t.isExpression(el)) {
        // 只要是括号包裹的表达式，直接转为JSExpression
        if (el.extra?.parenthesized || el.extra?.parenStart !== undefined) {
          const code = generate(el).code;
          return {
            type: 'JSExpression',
            value: `(${code})`,
          };
        }
        return parseLiteralValue(el);
      }
      return null;
    });
  }

  if (t.isObjectExpression(node)) {
    const result: Record<string, any> = {};
    node.properties.forEach((prop) => {
      if (t.isObjectProperty(prop) && t.isIdentifier(prop.key) && t.isExpression(prop.value)) {
        // 只要是括号包裹的表达式，直接转为JSExpression
        if (prop.value.extra?.parenthesized || prop.value.extra?.parenStart !== undefined) {
          const code = generate(prop.value).code;
          result[prop.key.name] = {
            type: 'JSExpression',
            value: `(${code})`,
          };
        } else {
          result[prop.key.name] = parseLiteralValue(prop.value);
        }
      }
    });
    return result;
  }

  if (t.isBinaryExpression(node)) {
    // 处理嵌套的 BinaryExpression - 增强版本，修复递归处理问题
    let leftValue = '';
    let rightValue = '';

    const left = node.left;
    const right = node.right;

    if (t.isMemberExpression(left)) {
      // 处理 this.constants.BaseURL 这种情况
      let current: t.Expression | t.V8IntrinsicIdentifier = left;
      let expression = '';
      while (t.isMemberExpression(current)) {
        const property = current.property;
        if (t.isIdentifier(property)) {
          expression = property.name + (expression ? '.' + expression : '');
        }
        current = current.object;
      }
      if (t.isThisExpression(current)) {
        expression = 'this.' + expression;
      } else if (t.isIdentifier(current)) {
        expression = current.name + '.' + expression;
      }
      leftValue = expression;
    } else if (t.isBinaryExpression(left)) {
      // 修复：递归处理嵌套的二元表达式
      const leftResult = parseLiteralValue(left);
      if (leftResult && typeof leftResult === 'object' && leftResult.type === 'JSExpression') {
        leftValue = leftResult.value;
      } else if (typeof leftResult === 'string') {
        leftValue = leftResult;
      } else {
        // 原来的特殊处理逻辑保持不变
        const leftLeft = left.left;
        const leftRight = left.right;
        if (t.isCallExpression(leftLeft)) {
          const callee = leftLeft.callee;
          if (t.isMemberExpression(callee)) {
            // 处理 this.utils.getGlobalData('BaseURL') 这种情况
            let current: t.Expression | t.V8IntrinsicIdentifier = callee;
            let expression = '';
            while (t.isMemberExpression(current)) {
              const property = current.property;
              if (t.isIdentifier(property)) {
                expression = property.name + (expression ? '.' + expression : '');
              }
              current = current.object;
            }
            if (t.isThisExpression(current)) {
              expression = 'this.' + expression;
            }
            // 添加函数调用的参数处理 - 修复：无论是否有参数都要添加括号
            if (leftLeft.arguments && leftLeft.arguments.length > 0) {
              expression +=
                '(' +
                leftLeft.arguments
                  .map((arg) => {
                    if (t.isStringLiteral(arg)) {
                      return `'${arg.value}'`;
                    }
                    if (t.isExpression(arg)) {
                      const processed = parseLiteralValue(arg);
                      if (processed === null) return '';
                      return typeof processed === 'string' ? processed : JSON.stringify(processed);
                    }
                    return '';
                  })
                  .filter(Boolean)
                  .join(', ') +
                ')';
            } else {
              // 即使没有参数也要添加空括号
              expression += '()';
            }
            leftValue = expression;
          }
        }
        if (t.isStringLiteral(leftRight)) {
          leftValue += ` + "${leftRight.value}"`;
        }
      }
    } else if (t.isConditionalExpression(left)) {
      // 处理左侧的三元操作符表达式
      const leftResult = parseLiteralValue(left);
      if (leftResult && typeof leftResult === 'object' && leftResult.type === 'JSExpression') {
        leftValue = `(${leftResult.value})`;
      } else {
        leftValue = String(leftResult || '');
      }
    } else if (t.isCallExpression(left)) {
      // 处理函数调用表达式
      const callee = left.callee;
      if (t.isMemberExpression(callee)) {
        let current: t.Expression | t.V8IntrinsicIdentifier = callee;
        let expression = '';
        while (t.isMemberExpression(current)) {
          const property = current.property;
          if (t.isIdentifier(property)) {
            expression = property.name + (expression ? '.' + expression : '');
          }
          current = current.object;
        }
        if (t.isThisExpression(current)) {
          expression = 'this.' + expression;
        }
        // 处理函数参数 - 修复：无论是否有参数都要添加括号
        if (left.arguments && left.arguments.length > 0) {
          expression +=
            '(' +
            left.arguments
              .map((arg) => {
                if (t.isStringLiteral(arg)) {
                  return `'${arg.value}'`;
                }
                if (t.isExpression(arg)) {
                  const processed = parseLiteralValue(arg);
                  if (processed === null) return '';
                  return typeof processed === 'string' ? processed : JSON.stringify(processed);
                }
                return '';
              })
              .filter(Boolean)
              .join(', ') +
            ')';
        } else {
          // 即使没有参数也要添加空括号
          expression += '()';
        }
        leftValue = expression;
      }
    } else if (t.isStringLiteral(left)) {
      // 处理字符串字面量，保留引号
      leftValue = `"${left.value}"`;
    } else {
      // 处理其他类型的左侧表达式
      if (t.isExpression(left)) {
        const leftResult = parseLiteralValue(left);
        if (leftResult && typeof leftResult === 'object' && leftResult.type === 'JSExpression') {
          leftValue = leftResult.value;
        } else if (leftResult !== null) {
          leftValue = String(leftResult);
        }
      }
    }

    // 处理右侧表达式
    if (t.isTemplateLiteral(right)) {
      rightValue = parseLiteralValue(right);
    } else if (t.isStringLiteral(right)) {
      rightValue = `"${right.value}"`;
    } else if (t.isConditionalExpression(right)) {
      // 处理三元操作符表达式，保留括号以保持优先级
      const rightResult = parseLiteralValue(right);
      if (rightResult && typeof rightResult === 'object' && rightResult.type === 'JSExpression') {
        rightValue = `(${rightResult.value})`;
      } else {
        rightValue = String(rightResult || '');
      }
    } else if (t.isMemberExpression(right)) {
      // 处理成员表达式
      let current: t.Expression | t.V8IntrinsicIdentifier = right;
      let expression = '';
      while (t.isMemberExpression(current)) {
        const property = current.property;
        if (t.isIdentifier(property)) {
          expression = property.name + (expression ? '.' + expression : '');
        }
        current = current.object;
      }
      if (t.isThisExpression(current)) {
        expression = 'this.' + expression;
      } else if (t.isIdentifier(current)) {
        expression = current.name + '.' + expression;
      }
      rightValue = expression;
    } else if (t.isBinaryExpression(right)) {
      // 递归处理嵌套的二元表达式
      const rightResult = parseLiteralValue(right);
      if (rightResult && typeof rightResult === 'object' && rightResult.type === 'JSExpression') {
        rightValue = `(${rightResult.value})`;
      } else {
        rightValue = String(rightResult || '');
      }
    } else if (t.isCallExpression(right)) {
      // 处理函数调用表达式
      const rightResult = parseLiteralValue(right);
      if (rightResult && typeof rightResult === 'object' && rightResult.type === 'JSExpression') {
        rightValue = rightResult.value;
      } else {
        rightValue = String(rightResult || '');
      }
    } else {
      // 其他类型的表达式，尝试通用解析
      const rightResult = parseLiteralValue(right);
      if (rightResult && typeof rightResult === 'object' && rightResult.type === 'JSExpression') {
        rightValue = rightResult.value;
      } else if (rightResult !== null) {
        rightValue = String(rightResult);
      }
    }

    return {
      type: 'JSExpression',
      value: `${leftValue} ${node.operator} ${rightValue}`,
    };
  }

  if (t.isArrowFunctionExpression(node) || t.isFunctionExpression(node)) {
    // 处理箭头函数和普通函数表达式 - 使用老版本的逻辑
    const params = node.params
      .map((param) => {
        if (t.isIdentifier(param)) {
          return param.name;
        }
        return 'param';
      })
      .join(', ');

    // 获取函数体
    let bodyCode = '';
    if (t.isBlockStatement(node.body)) {
      // 如果是块语句，直接使用原始代码
      const { code } = generate(node.body);
      bodyCode = code;
    } else if (t.isExpression(node.body)) {
      // 如果是表达式，生成表达式代码并添加return语句
      const { code } = generate(node.body);
      bodyCode = `{ return ${code}; }`;
    }

    // 生成函数名
    let functionName = 'dataHandler';
    if (
      (node as any).parent &&
      t.isObjectProperty((node as any).parent) &&
      t.isIdentifier((node as any).parent.key)
    ) {
      functionName = (node as any).parent.key.name;
    } else if (
      (node as any).parent?.parent &&
      t.isObjectProperty((node as any).parent?.parent) &&
      t.isIdentifier((node as any).parent?.parent.key)
    ) {
      functionName = (node as any).parent.parent.key.name;
    }

    // 生成完整的函数代码，保留原始函数体结构
    const functionCode = `function ${functionName}(${params}) ${bodyCode}`;
    logger('functionCode: ', functionCode);
    return {
      type: 'JSFunction',
      value: functionCode,
    };
  }

  if (t.isTemplateLiteral(node)) {
    // 处理模板字符串 - 从老版本复制的逻辑
    let str = '';
    for (let i = 0; i < node.quasis.length; i++) {
      str += node.quasis[i].value.raw;
      if (i < node.expressions.length) {
        const expression = node.expressions[i];
        if (t.isExpression(expression)) {
          const expr = parseLiteralValue(expression);
          if (expr !== null) {
            str += '${' + (typeof expr === 'object' && expr !== null ? expr.value : expr) + '}';
          }
        }
      }
    }
    return '`' + str + '`';
  }

  if (t.isNewExpression(node) && t.isIdentifier(node.callee) && node.callee.name === 'Date') {
    return 'NEW_DATE'; // 使用标识符
  }

  return null;
}

// 辅助函数：解析 TypeScript 类型字面量的字段结构
function parseTypeLiteralFields(
  typeLiteral: t.TSTypeLiteral,
  parentFieldName: string,
  logPrefix: string = '对象字面量',
): ITypeEntityField[] {
  const fields: ITypeEntityField[] = [];

  if (typeLiteral.members && typeLiteral.members.length > 0) {
    typeLiteral.members.forEach((member: any) => {
      if (t.isTSPropertySignature(member) && t.isIdentifier(member.key)) {
        const commentData = parseFieldComment(member.leadingComments);
        const subField: ITypeEntityField = {
          name: member.key.name,
          desc: commentData.desc,
          example: commentData.example,
          required: !member.optional,
          type: 'string', // 默认类型
          isArray: false,
          isApi: false,
        };

        // 解析子字段的类型
        if (member.typeAnnotation && t.isTSTypeAnnotation(member.typeAnnotation)) {
          const subTypeAnnotation = member.typeAnnotation.typeAnnotation;
          if (t.isTSStringKeyword(subTypeAnnotation)) {
            subField.type = 'string';
          } else if (t.isTSNumberKeyword(subTypeAnnotation)) {
            subField.type = 'number';
          } else if (t.isTSBooleanKeyword(subTypeAnnotation)) {
            subField.type = 'boolean';
          } else if (
            t.isTSObjectKeyword(subTypeAnnotation) ||
            t.isTSAnyKeyword(subTypeAnnotation)
          ) {
            subField.type = 'object';
          }
        }

        fields.push(subField);
        logger(
          `解析${logPrefix}子字段: ${parentFieldName}.${subField.name} (${subField.type})`,
        );
      }
    });
  }

  return fields;
}

// 辅助函数：从泛型类型中提取实际类型
function extractActualTypeFromGeneric(typeRef: t.TSTypeReference): string | null {
  logger(
    '提取泛型实际类型，原始类型:',
    t.isIdentifier(typeRef.typeName) ? typeRef.typeName.name : '非标识符类型名',
  );

  // 检查是否有泛型参数
  if (!typeRef.typeParameters || !t.isTSTypeParameterInstantiation(typeRef.typeParameters)) {
    logger('没有泛型参数');
    return null;
  }

  const params = typeRef.typeParameters.params;
  if (params.length === 0) {
    logger('泛型参数为空');
    return null;
  }

  // 获取第一个泛型参数
  const firstParam = params[0];

  // 检查是否为 any 类型
  if (t.isTSAnyKeyword(firstParam)) {
    logger('泛型参数为 any 类型，不提取具体类型');
    return null;
  }

  if (t.isTSTypeReference(firstParam) && t.isIdentifier(firstParam.typeName)) {
    const actualTypeName = firstParam.typeName.name;
    logger('提取到的实际类型名称:', actualTypeName);
    return actualTypeName;
  }

  logger('无法提取实际类型名称，参数类型:', firstParam.type);
  return null;
}
